#include <queue>
#include <iostream>
#include <pthread.h>

const int defaultcap = 5;

template <class T>
class BlockQueue
{
public:
    BlockQueue(int cap = defaultcap)
        : _capacity(cap), _csleep_num(0), _psleep_num(0)
    {
        pthread_mutex_init(&_mutex, NULL);
        pthread_cond_init(&_emptycond, NULL);
        pthread_cond_init(&_fullcond, NULL);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_emptycond);
        pthread_cond_destroy(&_fullcond);
    }

    void Equeue(const T &data)
    {
        // 生产者生产
        pthread_mutex_lock(&_mutex);

        while (IsFull()) // 所以这里用while增强健壮性，让其重复检查，以免满的时候push
        {
            _psleep_num++;
            // wait函数有可能会失败，失败后立即返回，但此时队列是满的，再push数据导致错误
            // wait可能会因为条件不满足而被唤醒，叫伪唤醒
            pthread_cond_wait(&_fullcond, &_mutex);
            _psleep_num--;
        }

        _q.push(data);

        if (_csleep_num > 0)
        {
            pthread_cond_signal(&_emptycond);
            std::cout << "唤醒消费者...." << std::endl;
        }
        // pthread_cond_signal(&_emptycond);//放解锁前面
        pthread_mutex_unlock(&_mutex);
        // pthread_cond_signal(&_emptycond);//放解锁后面
        // 两种都可以，一般选择放前面，放前面醒来后要继续竞争锁，但此时锁还未被释放，释放后可再竞争，若失败，则在锁那里阻塞等待
        // 放后面，同样竞争锁，若失败，则在锁那里阻塞等待
    }

    T Pop()
    {
        // 消费者消费
        pthread_mutex_lock(&_mutex);

        while (IsEmpty())
        {
            _csleep_num++;
            pthread_cond_wait(&_emptycond, &_mutex);
            _csleep_num--;
        }

        T data = _q.front();
        _q.pop();

        if (_psleep_num > 0)
        {
            pthread_cond_signal(&_fullcond);
            std::cout << "唤醒生产者...." << std::endl;
        }

        pthread_mutex_unlock(&_mutex);

        return data;
    }

private:
    std::queue<T> _q;
    pthread_mutex_t _mutex;
    pthread_cond_t _emptycond;
    pthread_cond_t _fullcond;
    int _capacity;
    int _csleep_num;
    int _psleep_num;

    bool IsEmpty()
    {
        return _q.empty();
    }

    bool IsFull()
    {
        return _q.size() >= _capacity;
    }
};